package itsm.isperp.module.controller.bpm;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.utils.JsonBuilder;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.bpm.BpmProcessRelation;
import itsm.isperp.module.entity.db.DbEntity;
import itsm.isperp.module.service.bpm.BpmProcessRelationService;
import itsm.isperp.module.service.bpm.BpmProcessSettingService;
import itsm.isperp.module.service.change.ChgChangeService;
import itsm.isperp.module.service.incident.IcdIncidentService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import me.chanjar.weixin.common.util.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * 关联流程控制器
 * 
 * @author lizx
 * @date 2014-7-21
 */
@Controller
@RequestMapping("bpm/processRelation")
public class BpmProcessRelationController extends
		BaseController<BpmProcessRelation> {

	@Autowired
	BpmProcessRelationService bpmProcessRelationService;

	@Override
	public BpmProcessRelationService getService() {
		return bpmProcessRelationService;
	}

	@Override
	public String getPageTitle() {
		return "关联流程";
	}

	@RequestMapping("listRelation")
	@ResponseBody
	public List<Map<String, Object>> listRelation(String id) {
		return this.bpmProcessRelationService.listRelation(id);

	}

	@RequestMapping("listProcess")
	@ResponseBody
	public PageResponse<Map<String, Object>> listProcess(String projectId,
			String processKey, JqGridRequest req) {
		return this.bpmProcessRelationService.listProcess(projectId,
				processKey, req); 
	}

	@RequestMapping("sourceView")
	public ModelAndView sourceView(String sourceId, String projectId,
			String processKey, String state) {

		ModelAndView mv = new ModelAndView("bpm/processRelation/sourceView");
		mv.addObject("sourceId", sourceId);
		mv.addObject("projectId", projectId);
		mv.addObject("processKey", processKey);
		mv.addObject("state", state);
		return mv;

	}

	// toid---->
	private void build(String id, String fromField, String toField,
			List<Map<String, Object>> r, Map<String, Object> rmm) {
		String sql = " SELECT COUNT(relation_type) rcount ,relation_type "
				+ " FROM  bpm_process_relation WHERE " + fromField + "='" + id
				+ "' GROUP BY  relation_type";

		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

		List<Map<String, Object>> l = jdbcTemplate.queryForList(sql);

		// 只有一种分类
		for (Map<String, Object> m : l) {
			int rcount = Integer.valueOf(m.get("rcount").toString());
			String relation_type = m.get("relation_type").toString();

			if (rcount > 3) {
				Map<String, Object> rm = new HashMap<>();
				rm.put("id", relation_type);
				rm.put("title", relation_type + "【" + rcount + "】");
				rm.put("type", relation_type);
				rmm.put("next", relation_type);
				r.add(rm);
			} else {

				String sql2 = " SELECT  " + toField
						+ " FROM  bpm_process_relation WHERE " + fromField
						+ "='" + id + "' ";
				List<String> tids = jdbcTemplate.queryForList(sql2,
						String.class);

				for (String tid : tids) {
					Map<String, Object> rm = new HashMap<>();
					rm.put("id", tid);
					rm.put("type", relation_type);
					rmm.put("next", tid);
					r.add(rm);
					build(tid, fromField, toField, r, rm);
				}
			}

		}

	}

	@RequestMapping("chartView")
	public ModelAndView chartView(String id, String projectId,
			String processKey, String state) {

		ModelAndView mv = new ModelAndView("bpm/processRelation/chartView");
		String flows = null;
		mv.addObject("id", id);

		id = "1";

		Map<String, Object> rm = new HashMap<>();
		rm.put("id", id);

		List<Map<String, Object>> r1 = new ArrayList<>();

		List<Map<String, Object>> r2 = new ArrayList<>();
		r1.add(rm);
		r2.add(rm);

		build(id, "from_id", "to_id", r1, rm);

		build(id, "to_id", "from_id", r2, rm);

		String s = JsonBuilder.buildNormalBinder().toJson(r1);
		String s2 = "";
		for (Map<String, Object> m : r1) {
			s2 += "<div class=\"before\" id=\"" + m.get("id") + "\" next=\""
					+ m.get("next") + "\">" + m.get("id") + "</div>";
		}

		mv.addObject("flows", s);
		return mv;

	}

	@RequestMapping(value = "getRelationTree")
	@ResponseBody
	public List<ITreeNode> getRelationTree(String id, String rootId, int way,
			HttpServletRequest req) {

		return this.getService().getRelationTree(id, rootId, way);
	}

	@RequestMapping("delete")
	@Override
	@ResponseBody
	public ResultMessage delete(String id, HttpServletRequest req) {
		// 如果关联的to_id所在的业务主表是草稿状态的，则删除
		BpmProcessRelation bpr = this.getService().findOne(id);
		if (bpr != null) {
			String toId = bpr.getToId();
			String toType = bpr.getToType();
			String tableName = "";

			BpmProcessSettingService bpmProcessSettingService = ContextHolder
					.getSpringBean("bpmProcessSettingService");
			DbEntity dbEntity = bpmProcessSettingService
					.findDbEntityByKey(toType);
			tableName = dbEntity.getTableName();
			String sql = "delete from " + tableName + " where id='" + toId
					+ "' and PROCESS_ID IS NULL";
			JdbcTemplate jdbcTemplate = ContextHolder
					.getSpringBean("jdbcTemplate");
			jdbcTemplate.execute(sql);
		}
		this.getService().delete(id);
		return ResultMessage.newInstance(true);
	}
	@RequestMapping("getRelateMainProcessInfoByBpmProFromId")
	@ResponseBody
	public ResultMessage getRelateMainProcessInfoByBpmProFromId(String id,
			String fkey, HttpServletRequest req) {
		if (id != null) {
			Map<String, Object> returnObject = new HashMap<String, Object>();
			if (StringUtils.isNotEmpty(fkey)) {
				switch (fkey) {
				case "incidentProcess":
					IcdIncidentService icdIncidentService = ContextHolder
							.getSpringBean("icdIncidentService");
					returnObject = icdIncidentService
							.findCusUserIncidentDetail(id);
					break;
				case "changeProcess":
					ChgChangeService chgChangeService = ContextHolder
							.getSpringBean("chgChangeService");
					returnObject = chgChangeService
							.findChangeRelateTaskDetail(id);
					break;
				}
			}
			if (returnObject != null)
				return ResultMessage.newInstance(true, fkey, returnObject);
			else
				return null;
		} else {
			return null;
		}
	}

	@RequestMapping("getRelateMainProcessInfoByBpmProToId")
	@ResponseBody
	public ResultMessage getRelateMainProcessInfoByBpmProToId(String id,
			HttpServletRequest req) {
		BpmProcessRelationService bpmProcessRelationService = ContextHolder
				.getSpringBean("bpmProcessRelationService");
		JqGridRequest jqReq = new JqGridRequest();
		jqReq.setPageable(false);
		jqReq.addFilterRule("to_id", JqGridFilterRuleOp.eq, id);
		BpmProcessRelation bpr = bpmProcessRelationService
				.findOneByRequest(jqReq);
		if (bpr != null) {
			String fId = bpr.getFromId();
			String fkey = bpr.getFromType();
			Map<String, Object> returnObject = new HashMap<String, Object>();
			if (id != null) {
				switch (fkey) {
				case "incidentProcess":
					IcdIncidentService icdIncidentService = ContextHolder
							.getSpringBean("icdIncidentService");
					returnObject = icdIncidentService
							.findCusUserIncidentDetail(fId);
					break;
				case "changeProcess":
					ChgChangeService chgChangeService = ContextHolder
							.getSpringBean("chgChangeService");
					returnObject = chgChangeService
							.findChangeRelateTaskDetail(fId);
					break;
				}
				if (returnObject != null)
					return ResultMessage.newInstance(true, fkey, returnObject);
				else
					return null;
			} else {
				return null;
			}
		} else {
			return null;
		}

	}
}
